<template>
  <el-card class="list-page">
    <div class="list-h">
      <span
        @click="goBack"
        style="
          color: #5298ff;
          position: absolute;
          top: -42px;
          z-index: 7777;
          right: 20px;
          cursor: pointer;
        "
        >返回</span
      >
      <div>
        <el-button
          type="primary"
          @click="handleOperate('add')"
          v-auth="`/projectsS/document--add`"
          >新增</el-button
        >
        <!-- <el-button type="primary" @click="handleDownload('bath')" v-auth="`/projectsS/document--bath`">批量下载</el-button> -->
      </div>

      <el-form
        :inline="true"
        :model="formInline"
        ref="formRef"
        class="demo-form-inline"
      >
        <el-form-item label="文档名称" prop="documentNameLike">
          <el-input
            class="width-custom120"
            v-model="formInline.documentNameLike"
          />
        </el-form-item>
        <el-form-item label="文档类型" prop="documentTypePathName">
          <el-cascader
            class="width-custom120"
            v-model="documentType"
            clearable
            filterable
            :options="documentTypeList"
            :props="documentProp"
            @change="changeType"
            placeholder="输入名称搜索"
          />
        </el-form-item>

        <el-form-item label="文件类型" prop="docType">
          <el-select
            clearable
            class="width-custom120"
            v-model="formInline.docType"
          >
            <el-option
              v-for="item in docTypeList"
              :label="item.dicValue"
              :key="item.dicCode"
              :value="item.dicCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目阶段" prop="projectPhaseCode">
          <el-select
            clearable
            class="width-custom120"
            v-model="formInline.projectPhaseCode"
          >
            <el-option
              v-for="item in projectPhaseList"
              :label="item.dicValue"
              :key="item.dicCode"
              :value="item.dicCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建人" prop="createUserNameLike">
          <el-input
            class="width-custom120"
            v-model="formInline.createUserNameLike"
          />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            class="width-custom230"
            v-model="timeValue"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
            @change="handleChangeDate"
          />
        </el-form-item>

        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
          <el-button
            type="primary"
            @click="handleSearch"
            v-auth="`/projectsS/document--query`"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-skeleton
      style="height: calc(100vh - 340px)"
      :rows="8"
      :loading="loading"
      animated
    >
    </el-skeleton>
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      v-loading="loading"
      v-show="!loading"
      :height="'calc(100vh - 340px)'"
      :header-cell-style="{
        background: '#F7F9FD',
        color: '#000',
        height: '48px',
        borderTop: '1px soild #E4E8F2'
      }"
      :row-class-name="tableRowClassName"
    >
      <template #empty>
        <el-empty :image-size="150" description="暂无数据"></el-empty>
      </template>

      <el-table-column type="index" label="序号" width="80">
        <template v-slot="scope">
          <span>{{
            (pageState.pageNum - 1) * pageState.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="documentName"
        label="文档名称"
      >
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="documentTypePathName"
        label="文档类型"
      >
      </el-table-column>
      <el-table-column prop="docTypeName" label="文件类型"> </el-table-column>
      <el-table-column prop="projectPhaseName" label="项目阶段">
      </el-table-column>
      <el-table-column prop="createUserName" label="创建人"> </el-table-column>
      <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="{ row }">
          <el-button
            type="text"
            size="small"
            @click="handlePreview(row)"
            v-auth="`/projectsS/document--preview`"
            >预览</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="handleDownload('down', row)"
            v-auth="`/projectsS/document--downLoad`"
            >下载</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="handleOperate('edit', row)"
            v-auth="`/projectsS/document--edit`"
            >编辑</el-button
          >
          <el-button
            type="text"
            v-auth="`/projectsS/document--delete`"
            @click="showDeleteMessageBox(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <re-pagination
      v-if="total > 0"
      :total="total"
      v-model:page="pageState.pageNum"
      v-model:limit="pageState.pageSize"
      @pagination="handleChangePage"
    />

    <document
      v-if="dialogForm.visible"
      :title="dialogForm.title"
      :dialogType="dialogForm.type"
      :fileItem="fileItem"
      @cancel="dialogForm.visible = false"
      @submit="submit"
    ></document>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import RePagination from "/@/components/RePagination/index.vue";
import { ElMessageBox } from "element-plus";
import document from "./components/document.vue";
// import { download } from "/@/utils/download";
import * as api from "/@/api/document";
import { storageLocal } from "/@/utils/storage";
import { downloadFile } from "/@/utils/ecm";
import {
  getBimAccessToken,
  getFileViewToken,
  getTranslateStatus
} from "/@/utils/bim";
const formRef = ref<HTMLFormElement | null>(null) as any;
const documentProp = ref({
  label: "documentTypeName",
  children: "children",
  value: "documentTypeCode",
  checkStrictly: true
});
let projectPhaseList = ref([]);
let documentType = ref(null);
const initData = {
  // TODO 接口未出，后续根据字段直接替换
  documentNameLike: "",
  documentTypeCode: "", //
  docType: "", //
  moduleType: "5",
  createUserNameLike: "", //
  createTimeStrStart: "", //
  createTimeStrEnd: "", //
  projectPhaseCode: "", //
  documentTypePathName: "",
  projectManageId: storageLocal.getItem("projectInfo")?.id,
  ext1: storageLocal.getItem("sectionInfo")?.id
};

const formInline = reactive(initData);

const timeValue = ref(null);
const documentTypeList = ref([]);
const docTypeList = ref([]);
const tableData = ref([]);
const pageState = reactive({
  pageNum: 1,
  pageSize: 10
});

const dialogForm = reactive({
  type: "add",
  visible: false,
  title: "添加文档"
});
const fileId = ref("");
const fileItem = ref({});
const router = useRouter();
const loading = ref<boolean>(false);
const total = ref<number>(0);
const formParams = ref<typeof initData>({ ...initData });

// //选择文档类型
// const changeType = value => {
//   let str = "";
//   value &&
//     value.map((el, index) => {
//       const docObj = getDocTypeAuth(documentTypeList.value, el);
//       const path = index === value.length - 1 ? "" : "/";
//       str += docObj.documentTypeName + path;
//     });
//   formInline.documentTypeName = str;
// };

// const getDocTypeAuth = (nodes, searchKey) => {
//   for (let _i = 0; _i < nodes.length; _i++) {
//     if (nodes[_i].documentTypeCode === searchKey) {
//       return nodes[_i];
//     } else {
//       if (nodes[_i].children && nodes[_i].children.length > 0) {
//         const res = getDocTypeAuth(nodes[_i].children, searchKey);
//         if (res) {
//           return res;
//         }
//       }
//     }
//   }
//   return null;
// };

const changeType = value => {
  let str = "";
  value &&
    value.map((el, index) => {
      const docObj = getDocTypeAuth(documentTypeList.value, el);
      const path = index === value.length - 1 ? "" : "/";
      str += docObj.documentTypeName + path;
    });
  formInline.documentTypePathName = str;
};

const getDocTypeAuth = (nodes, searchKey) => {
  for (let _i = 0; _i < nodes.length; _i++) {
    if (nodes[_i].documentTypeCode === searchKey) {
      return nodes[_i];
    } else {
      if (nodes[_i].children && nodes[_i].children.length > 0) {
        const res = getDocTypeAuth(nodes[_i].children, searchKey);
        if (res) {
          return res;
        }
      }
    }
  }
  return null;
};

const goBack = () => {
  const projectTypeCode = storageLocal.getItem("projectInfo")?.projectTypeCode;
  if (["B", "S"].includes(projectTypeCode)) {
    router.push(`/projectsB/manage/archives`);
    return;
  }
  router.push(`/projectsA/proManage/section`);
};

const initProjectPhaseList = async () => {
  try {
    const params = {
      dicType: "flow_project_phase"
    };
    const { code, data } = await api.postDictList(params);
    projectPhaseList.value = data;
    console.log(code, data);
  } catch (err) {
    console.log(err);
  }
};

//获取数据列表
const getTableList = async (obj: object = {}) => {
  try {
    loading.value = true;
    const { code, data } = await api.fileList({
      ...obj,
      ...pageState
    });
    if (code === 200) {
      tableData.value = data.list;
      total.value = data.rows;
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
};

//改变时间
const handleChangeDate = item => {
  if (item) {
    formInline.createTimeStrStart = item[0];
    formInline.createTimeStrEnd = item[1];
  } else {
    formInline.createTimeStrStart = "";
    formInline.createTimeStrEnd = "";
  }
};

const handleReset = () => {
  formRef.value.resetFields();
  timeValue.value = null;
  documentType.value = null;
  handleChangeDate(null);
  formParams.value = initData;
  getTableList(formInline);
};

const handleSearch = () => {
  pageState.pageNum = 1;
  formParams.value = formInline;
  getTableList(formInline);
};

const handleChangePage = () => {
  getTableList(formParams.value);
};

const handleDownload = (type, row) => {
  if (type === "down") {
    const item = row.documentAttachmentArr[0];
    if (!item) return;
    downloadFile(item.uuidFile, item.fileName);
  } else if (type === "bath") {
    router.replace({
      path: "/projectsS/document/engineering/download",
      query: {
        mode: "project"
      }
    });
  }
};

const handlePreview = async row => {
  if (row.docType === "2" || row.docType === "3") {
    let documentAttachment = row.documentAttachmentArr[0];
    const bimInfo = JSON.parse(documentAttachment.bimInfo);
    const res = await getTranslateStatus(bimInfo.fileId);
    if (res.status === "success") {
      const viewToken = await getFileViewToken(bimInfo.fileId);
      window.open(
        `${location.origin}${location.pathname}#/preview3D?viewToken=${viewToken}`
      );
    } else {
      NotifMessage.warning("模型转换中，请稍后再试！");
    }
  } else {
    window.open(
      `${location.origin}${location.pathname}#/preview?uuidFile=${row.documentAttachmentArr[0].uuidFile}&fileName=${row.documentAttachmentArr[0].fileName}`
    );
  }
};

const handleOperate = (type, row) => {
  dialogForm.type = type;
  if (type === "edit") {
    fileId.value = row.id;
    getDetail(row);
    dialogForm.title = "编辑文档";
  } else {
    dialogForm.title = "添加文档";
    dialogForm.visible = true;
  }
};

const submit = formState => {
  if (dialogForm.type === "add") {
    handleAdd(formState);
  } else if (dialogForm.type === "edit") {
    handleUpdate(formState);
  }
};

const getDetail = async row => {
  const { code, data } = await api.fileInfo(row);
  if (code === 200) {
    fileItem.value = data;
    dialogForm.visible = true;
    // fileItem.value.documentAttachmentArr = data.documentAttachmentArr;
    // defaultFileList.value = onInitFileList(documentAttachmentArr);
  }
};

const handleAdd = async formState => {
  try {
    const { code, message } = await api.fileAdd(formState);
    if (code === 200) {
      getTableList(formParams.value);
      NotifMessage.success("新增文档成功");
      dialogForm.visible = false;
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

const handleUpdate = async formState => {
  try {
    const { code, message } = await api.fileUpdate(
      Object.assign(formState, { id: fileId.value })
    );
    console.log(code, message);
    if (code === 200) {
      getTableList(formParams.value);
      NotifMessage.success("修改成功");
      dialogForm.visible = false;
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};
const showDeleteMessageBox = row => {
  ElMessageBox.confirm("确定删除该条记录吗？", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    iconClass: "el-icon-warning"
  })
    .then(() => {
      handleDelete(row);
    })
    .catch(() => {});
};

const handleDelete = async row => {
  try {
    const { code, message } = await api.fileDelete({
      id: row.id
    });
    if (code === 200) {
      NotifMessage.success("删除成功");
      getTableList(formParams.value);
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

// 获取文档类型
const initDoucumentTypeList = async () => {
  try {
    const { data } = await api.getTreeDocumentType();
    documentTypeList.value = data;
  } catch (err) {
    console.log(err);
  }
};

// 获取文件类型
const initDocTypeList = async () => {
  try {
    const { data } = await api.postDictList({ dicType: "thd_doc_type" });
    docTypeList.value = data;
  } catch (err) {
    console.log(err);
  }
};

const tableRowClassName = ({ rowIndex }) => {
  if (rowIndex % 2 == 1) {
    return "odd-row";
  } else {
    return "";
  }
};

onMounted(async () => {
  initProjectPhaseList();
  initDoucumentTypeList();
  initDocTypeList();
  await getBimAccessToken();
});
getTableList(formInline);
</script>
<style>
.el-icon-warning {
  color: #e45d5d !important;
}
</style>
<style scoped lang="scss">
.redColor {
  width: 10px;
  height: 10px;
  background: #f5a623;
  border-radius: 50%;
  display: inline-block;
}

.greenColor {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #21d371;
  display: inline-block;
}

.grayColor {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #979797;
  display: inline-block;
}

:deep .el-dialog__body {
  padding: 20px !important;
}

:deep .el-table__row.odd-row {
  background: #fdfdff;
}
</style>
